<template>
  <el-dialog
    :title="isEdit ? '编辑任务' : '新建任务'"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    width="600px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入任务名称" />
      </el-form-item>
      
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="选择结束时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="负责人" prop="assignee">
            <el-input v-model="form.assignee" placeholder="请输入负责人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="选择优先级" style="width: 100%">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="上级任务" prop="parentId">
        <el-select 
          v-model="form.parentId" 
          placeholder="选择上级任务（可选）" 
          style="width: 100%"
          clearable
          @change="handleParentChange"
        >
          <el-option label="无上级任务" :value="null" />
          <el-option
            v-for="task in availableParentTasks"
            :key="task.id"
            :label="getTaskDisplayName(task)"
            :value="task.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="前置任务" prop="dependencies">
        <el-select 
          v-model="dependencies" 
          placeholder="选择前置任务（可选）" 
          style="width: 100%"
          multiple
          clearable
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option
            v-for="task in availableDependencyTasks"
            :key="task.id"
            :label="getTaskDisplayName(task)"
            :value="String(task.id)"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="选择状态" style="width: 100%">
          <el-option label="待开始" value="pending" />
          <el-option label="进行中" value="in-progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="进度" prop="progress">
        <el-slider
          v-model="form.progress"
          :min="0"
          :max="100"
          :show-tooltip="true"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="颜色" prop="color">
        <el-color-picker v-model="form.color" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import dayjs from 'dayjs'

export default {
  name: 'TaskEditDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    task: {
      type: Object,
      default: null
    },
    allTasks: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'save'],
  setup(props, { emit }) {
    const formRef = ref(null)
    
    const form = reactive({
      id: '',
      name: '',
      startDate: null,
      endDate: null,
      progress: 0,
      color: '#409EFF',
      assignee: '',
      priority: 'medium',
      status: 'pending',
      level: 0,
      parentId: null,
      dependencies: []
    })
    
    const rules = {
      name: [
        { required: true, message: '请输入任务名称', trigger: 'blur' }
      ],
      startDate: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      endDate: [
        { required: true, message: '请选择结束时间', trigger: 'change' }
      ]
    }
    
    const isEdit = computed(() => {
      return props.task && props.task.id
    })
    
    // 可选的上级任务列表（排除当前任务及其子任务）
    const availableParentTasks = computed(() => {
      if (!props.allTasks || props.allTasks.length === 0) {
        return []
      }
      
      // 如果是编辑模式，需要排除当前任务及其所有子任务
      if (isEdit.value && props.task) {
        const excludeIds = new Set([props.task.id])
        
        // 递归收集所有子任务ID
        const collectChildIds = (taskId) => {
          const children = props.allTasks.filter(t => t.parentId === taskId)
          children.forEach(child => {
            excludeIds.add(child.id)
            collectChildIds(child.id)
          })
        }
        collectChildIds(props.task.id)
        
        return props.allTasks.filter(task => !excludeIds.has(task.id))
      }
      
      return props.allTasks
    })
    
    // 可选的前置任务列表（排除当前任务及其子任务，以及已经选择的前置任务）
    const availableDependencyTasks = computed(() => {
      if (!props.allTasks || props.allTasks.length === 0) {
        return []
      }
      
      // 如果是编辑模式，需要排除当前任务及其所有子任务
      if (isEdit.value && props.task) {
        const excludeIds = new Set([String(props.task.id)])
        
        // 递归收集所有子任务ID
        const collectChildIds = (taskId) => {
          const children = props.allTasks.filter(t => String(t.parentId) === String(taskId))
          children.forEach(child => {
            excludeIds.add(String(child.id))
            collectChildIds(child.id)
          })
        }
        collectChildIds(props.task.id)
        
        // 排除已经选择的前置任务（避免循环依赖）
        if (dependencies.value && dependencies.value.length > 0) {
          dependencies.value.forEach(depId => {
            excludeIds.add(String(depId))
          })
        }
        
        const availableTasks = props.allTasks.filter(task => !excludeIds.has(String(task.id)))
        return availableTasks
      }
      
      // 新建模式，排除已经选择的前置任务
      const excludeIds = new Set()
      if (dependencies.value && dependencies.value.length > 0) {
        dependencies.value.forEach(depId => {
          excludeIds.add(String(depId))
        })
      }
      
      const availableTasks = props.allTasks.filter(task => !excludeIds.has(String(task.id)))
      return availableTasks
    })
    
    // 获取任务的显示名称（包含层级缩进）
    const getTaskDisplayName = (task) => {
      if (!task) return ''
      const indent = '　'.repeat(task.level || 0) // 使用全角空格作为缩进
      return `${indent}${task.name}`
    }
    
    // 确保dependencies始终是字符串数组
    const dependencies = computed({
      get: () => {
        return (form.dependencies || []).map(dep => String(dep))
      },
      set: (value) => {
        form.dependencies = value.map(dep => String(dep))
      }
    })
    
    // 处理上级任务变化
    const handleParentChange = (parentId) => {
      if (parentId) {
        const parentTask = props.allTasks.find(t => t.id === parentId)
        if (parentTask) {
          form.level = (parentTask.level || 0) + 1
        }
      } else {
        form.level = 0
      }
    }
    
    // 监听task变化，更新表单
    watch([() => props.task, () => props.allTasks], ([newTask, allTasks]) => {
      if (newTask && allTasks && allTasks.length > 0) {
        // 确保dependencies是字符串ID数组
        const dependencies = (newTask.dependencies || []).map(dep => String(dep))
        
        Object.assign(form, {
          id: newTask.id || '',
          name: newTask.name || '',
          startDate: newTask.startDate ? dayjs(newTask.startDate) : null,
          endDate: newTask.endDate ? dayjs(newTask.endDate) : null,
          progress: newTask.progress || 0,
          color: newTask.color || '#409EFF',
          assignee: newTask.assignee || '',
          priority: newTask.priority || 'medium',
          status: newTask.status || 'pending',
          level: newTask.level || 0,
          parentId: newTask.parentId || null,
          dependencies: dependencies
        })
      } else if (!newTask) {
        // 重置表单
        Object.assign(form, {
          id: '',
          name: '',
          startDate: dayjs(),
          endDate: dayjs().add(7, 'days'),
          progress: 0,
          color: '#409EFF',
          assignee: '',
          priority: 'medium',
          status: 'pending',
          level: 0,
          parentId: null,
          dependencies: []
        })
      }
    }, { immediate: true })
    
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        
        const taskData = {
          ...form,
          startDate: form.startDate,
          endDate: form.endDate,
          dependencies: dependencies.value
        }
        
        emit('save', taskData)
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }
    
    return {
      formRef,
      form,
      rules,
      isEdit,
      availableParentTasks,
      availableDependencyTasks,
      getTaskDisplayName,
      dependencies,
      handleParentChange,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 前置任务选择器样式 */
.el-select[multiple] .el-select__tags {
  max-width: calc(100% - 30px);
}

.el-select[multiple] .el-tag {
  margin: 2px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 任务层级缩进样式 */
.el-select-dropdown__item {
  font-family: 'Courier New', monospace;
}

/* 表单间距优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}
</style> 